import 'dart:async';
import 'package:logger/logger.dart';
import 'config/report_sdk_config.dart';
import 'report_delegate.dart';

class ReportSdk {
  static ReportSdk? _instance;
  ReportSdk._();

  static Future<ReportSdk> init({
    required String serverUrl,
    required String userId,
    DateTime Function()? now, //事件上报时间外面传入
    int batchSize = 25, //这个是后台默认一次最大支持25个事件
    int retentionDays = 7,
    Duration timeout = const Duration(seconds: 30),
    Duration batchTimeout = const Duration(seconds: 5),
    Duration retryInterval = const Duration(seconds: 1),
    Map<String, String> headers = const {},
    Logger? logger,
  }) async {
    if (_instance == null) {
      ReportSdkConfig(
        serverUrl: serverUrl,
        userId: userId,
        now: now ?? ReportSdkConfig.systemNow,
        batchSize: batchSize,
        retentionDays: retentionDays,
        timeout: timeout,
        batchTimeout: batchTimeout,
        retryInterval: retryInterval,
        headers: headers,
        logger: logger,
      );
      ReportSdkConfig.i.logger?.d("start init ReportSdk...");
      ReportSdkConfig.i.logger?.d(
        "params: headers=${ReportSdkConfig.i.headers}, serverUrl=${ReportSdkConfig.i.serverUrl}, userId=${ReportSdkConfig.i.userId}",
      );
      await ReportDelegate.getInstance();
      _instance = ReportSdk._();
      ReportSdkConfig.i.logger?.d("SDK init finished");
    } else {
      ReportSdkConfig.i.logger?.d("SDK already init");
    }
    return _instance!;
  }

  static ReportSdk get instance {
    assert(_instance != null, 'ReportSdk must be invited first');
    return _instance!;
  }

  static Future<void> destroy() async {
    await _instance?.dispose();
    _instance = null;
  }

  Future<void> reportEvent(String name, Map<String, dynamic> params) async {
    final webBeacon = await ReportDelegate.getInstance();
    webBeacon.reportEvent(name, params);
  }

  //app进入后台时也立即触发一次 report 无参数 triggerReport
  Future<void> triggerReport() async {
    final webBeacon = await ReportDelegate.getInstance();
    webBeacon.triggerReport();
  }

  //如果有要销毁资源
  Future<void> dispose() async {
    final webBeacon = await ReportDelegate.getInstance();
    webBeacon.dispose();
    _instance = null;
  }
}
